package com.zwps.biz.domain.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zwps.biz.api.model.vo.elements.*;
import com.zwps.biz.dal.db.dao.ElementsDAO;

import com.zwps.biz.domain.service.ElementsService;
import com.zwps.biz.domain.service.PubPointAllService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
@Slf4j
public class ElementsServiceImpl implements ElementsService {

    @Autowired
    private ElementsDAO elementsDAO;
    @Autowired
    PubPointAllService pubPointAllService;


    @Override
    public List<ElementsDownstreamVO> getElementsDownstream() {
        return elementsDAO.getElementsDownstream();
    }

    @Override
    public List<ElementsReservoirAreaVO> getElementsReservoirArea() {
        return elementsDAO.getElementsReservoirArea();
    }

    @Override
    public List<RelicPatternSpotVO> getRelicPatternSpot() {
        return elementsDAO.getRelicPatternSpot();
    }

    @Override
    public List<SectionDownstreamVO> getSectionDownstream() {
        return elementsDAO.getSectionDownstream();
    }

    @Override
    public ReservoirInundationStatsVO selectReservoirInundationByWaterlevel(BigDecimal waterlevel) {
        List<ReservoirInundationVO> reservoirInundationVOList = elementsDAO.selectReservoirInundationByWaterlevel(waterlevel);
        ReservoirInundationStatsVO reservoirInundationStatsVO = disposeStats(reservoirInundationVOList, new ArrayList<>());
        return reservoirInundationStatsVO;
    }

    @Override
    public List<ReservoirInundationStatsVO> selectReservoirInundationByWaterlevels(BigDecimal[] numbers) {
        List<ReservoirInundationVO> reservoirInundationVOList = elementsDAO.selectReservoirInundation();
        Map<BigDecimal, List<ReservoirInundationVO>> reservoirInundationMap = reservoirInundationVOList.stream()
                .collect(Collectors.groupingBy(ReservoirInundationVO::getWaterlevel));

        List<RelicPatternSpotVO> relicPatternSpotList = elementsDAO.getRelicPatternSpotByType("下游");

        List<BigDecimal> sortedKeys = new ArrayList<>(reservoirInundationMap.keySet());
        Collections.sort(sortedKeys);

        List<ReservoirInundationStatsVO> list = new ArrayList<>();
        for (BigDecimal number : numbers) {
            int index = Collections.binarySearch(sortedKeys, number);
            List<ReservoirInundationVO> value;
            if (index >= 0) {
                // 找到完全匹配的值
                BigDecimal exactKey = sortedKeys.get(index);
                value = reservoirInundationMap.get(exactKey);
            }
            else {
                int insertionPoint = -(index + 1);
                BigDecimal lower = null;
                BigDecimal upper = null;

                if (insertionPoint > 0) {
                    lower = sortedKeys.get(insertionPoint - 1);
                }
                if (insertionPoint < sortedKeys.size()) {
                    upper = sortedKeys.get(insertionPoint);
                }

                BigDecimal closestKey;
                if (lower == null) {
                    closestKey = upper;
                } else if (upper == null) {
                    closestKey = lower;
                } else {
                    // 计算差值
                    BigDecimal lowerDiff = number.subtract(lower).abs();
                    BigDecimal upperDiff = upper.subtract(number).abs();
                    closestKey = lowerDiff.compareTo(upperDiff) <= 0 ? lower : upper;
                }
                value = reservoirInundationMap.get(closestKey);
            }
            list.add(disposeStats(value, relicPatternSpotList));
        }
        return list;
    }

    @Override
    public List<BigDecimal> getWaterlevel() {
        return elementsDAO.getWaterlevel();
    }

    @Override
    public ReservoirSubmergenceStatsVO selectReservoirSubmergenceByYear(Integer year,BigDecimal level,Integer status) {
        List<ReservoirInundationVO> reservoirSubmergenceVOList = elementsDAO.selectReservoirSubmergenceByYear(year, level, status);
        Map<String, ReservoirInundationVO> groupedVillageMap = reservoirSubmergenceVOList.stream()
                .collect(Collectors.groupingBy(
                        ReservoirInundationVO::getVillage, // 按 village 分组
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> {
                                    // 取该 village 的第一条记录（也可以选其它逻辑，如最新时间等）
                                    ReservoirInundationVO first = list.get(0);
                                    // 对该 village 所有记录的 population 求和
                                    Integer totalPopulation = list.stream()
                                            .map(ReservoirInundationVO::getPopulation)
                                            .filter(p -> p != null) // 避免 null 值影响求和
                                            .reduce(0, Integer::sum);
                                    ReservoirInundationVO summaryVo = new ReservoirInundationVO();
                                    summaryVo.setVillage(first.getVillage());
                                    summaryVo.setName(first.getName());
                                    summaryVo.setTown(first.getTown());
                                    summaryVo.setWaterlevel(first.getWaterlevel());
                                    summaryVo.setArea(first.getArea());
                                    summaryVo.setCount(first.getCount());
                                    summaryVo.setPopulation(totalPopulation);
                                    summaryVo.setStructure(first.getStructure());
                                    summaryVo.setType(first.getType());
                                    summaryVo.setCategory(first.getCategory());
                                    summaryVo.setYear(first.getYear());
                                    summaryVo.setDistrict(first.getDistrict());
                                    summaryVo.setTime(first.getTime());
                                    summaryVo.setLon(first.getLon());
                                    summaryVo.setLat(first.getLat());
                                    summaryVo.setEln(first.getEln());
                                    return summaryVo;
                                }
                        )
                ));
        List<ReservoirInundationVO> resultVOList = groupedVillageMap.values().stream().collect(Collectors.toList());
        ReservoirSubmergenceStatsVO vo= elementsDAO.selectReservoirSubmergence(year,level,status);
        vo.setTownList(elementsDAO.getTownList(year,level,status));
        vo.setVillageList(resultVOList);
        List<ReservoirInundationCountVO> count=new ArrayList<>();
        count.add(new ReservoirInundationCountVO("库区关键要素", elementsDAO.counts(year,level,status,5)));
        count.add(new ReservoirInundationCountVO("文物图斑", elementsDAO.counts(year,level,status,6)));


        vo.setCount(count);
        return vo;
    }


    public ReservoirSubmergenceStatsVO selectInundationByWaterlevel(BigDecimal waterlevel) {
        List<ElementsReservoirAreaVO> elementsReservoirAreaList = elementsDAO.getElementsList();
        List<ReservoirInundationVO> reservoirSubmergenceVOList = elementsDAO.selectInundationByWaterlevel(waterlevel);
        List<RelicPatternSpotVO> elementsPatternSpotList = elementsDAO.getElementList();
        Map<Integer, List<ReservoirInundationVO>> dataByType = reservoirSubmergenceVOList.stream()
                .collect(Collectors.groupingBy(ReservoirInundationVO::getType));
        ReservoirSubmergenceStatsVO vo= elementsDAO.selectInundation(waterlevel);
        vo.setTownList(elementsDAO.getTownLists(waterlevel));
        vo.setVillageList(dataByType.get(4));
        List<ReservoirInundationVO> kqgjysData = dataByType.get(6);
        List<String> names = kqgjysData.stream()
                .map(ReservoirInundationVO::getName).distinct()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<ElementsReservoirAreaVO> element = elementsReservoirAreaList.stream()
                .filter(ElementsReservoirAreaVO -> names.contains(ElementsReservoirAreaVO.getName()))
                .collect(Collectors.toList());
        vo.setKqgjysList(element);
        vo.setCount(elementsDAO.count(waterlevel));
        List<ReservoirInundationVO> wwtbData = dataByType.get(7);
        List<String> name = wwtbData.stream()
                .map(ReservoirInundationVO::getName).distinct()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<RelicPatternSpotVO> elements = elementsPatternSpotList.stream()
                .filter(RelicPatternSpotVO -> name.contains(RelicPatternSpotVO.getName()))
                .collect(Collectors.toList());

        vo.setWwtbList(elements);
        return vo;
    }

    @Override
    public Map<String, Object> selectReservoirSubmergenceDate(Integer year, BigDecimal level, Integer status) {
        List<VillageVO> village = elementsDAO.getVillageList();
        List<RelicPatternSpotVO> elementsPatternSpotList = elementsDAO.getElementList();
        List<ReservoirInundationDataVO> inundationList = new ArrayList<>();
        if (status!=4) {
            // Get water date data
            Object wDate = pubPointAllService.getWDate(year.toString());
            JSONArray jsonArray = wDate == null ? new JSONArray() : new JSONArray(JSONUtil.toJsonStr(wDate));
            List<BigDecimal> waterLevelList = jsonArray.stream()
                    .map(obj -> (JSONObject) obj)
                    .map(obj -> obj.getBigDecimal("waterLevelStart"))
                    .map(value -> value != null ? value : BigDecimal.ZERO)
                    .collect(Collectors.toList());
            Map<Integer, BigDecimal> waterLevelTimeMap = jsonArray.stream()
                    .map(obj -> (JSONObject) obj)
                    .filter(obj -> obj.getBigDecimal("waterLevelStart") != null && obj.getInt("time") != null)
                    .collect(Collectors.toMap(
                            obj -> obj.getInt("time"),
                            obj -> obj.getBigDecimal("waterLevelStart"),
                            (oldVal, newVal) -> oldVal,
                            LinkedHashMap::new
                    ));


            List<ReservoirInundationVO> bigDecimalList = elementsDAO.batchSelectReservoirInundation();
            Map<BigDecimal, List<ReservoirInundationVO>> bigDecimalListMap = bigDecimalList.stream()
                    .collect(Collectors.groupingBy(ReservoirInundationVO::getWaterlevel));

            Map<Integer, List<ReservoirInundationVO>> result = new HashMap<>();
// 提取所有实际有数据的 waterlevel
            Set<BigDecimal> availableWaterLevels = bigDecimalListMap.keySet();
            for (Map.Entry<Integer, BigDecimal> map : waterLevelTimeMap.entrySet()) {
                BigDecimal targetWaterLevel = map.getValue();
                // 情况 1：完全匹配的 waterlevel 存在
                if (bigDecimalListMap.containsKey(targetWaterLevel)) {
                    result.put(map.getKey(), bigDecimalListMap.get(targetWaterLevel));
                }
                // 情况 2：不存在完全匹配的，查找离它最近的一个水位
                else if (!availableWaterLevels.isEmpty()) {
                    BigDecimal closestWaterLevel = null;
                    BigDecimal minDiff = null;

                    for (BigDecimal existingWaterLevel : availableWaterLevels) {
                        BigDecimal diff = existingWaterLevel.subtract(targetWaterLevel).abs();
                        if (minDiff == null || diff.compareTo(minDiff) < 0) {
                            minDiff = diff;
                            closestWaterLevel = existingWaterLevel;
                        }
                    }

                    // 找到了离 targetWaterLevel 最近的一个水位，取该水位对应的数据
                    if (closestWaterLevel != null) {
                        result.put(map.getKey(), bigDecimalListMap.get(closestWaterLevel));
                    } else {
                        // 理论上不会走到这里，因为 availableWaterLevels 非空
                        result.put(map.getKey(), Collections.emptyList());
                    }
                }
                // 情况 3：bigDecimalListMap 中没有任何水位数据（空的 Map）
                else {
                    result.put(map.getKey(), Collections.emptyList());
                }
            }


            for (Map.Entry<Integer, List<ReservoirInundationVO>> entry : result.entrySet()) {
                Integer key = entry.getKey();
                List<ReservoirInundationVO> value = entry.getValue();
                inundationList.add(buildReservoirInundationData(value, key,village,elementsPatternSpotList));
            }
            inundationList.sort(Comparator.comparing(ReservoirInundationDataVO::getTime));
            if (inundationList.size() > 0) {
                inundationList.remove(0);
            }
        }
            List<ReservoirInundationDataVO> submergenceList = processSubmergenceData(year, level, status,village,elementsPatternSpotList);

        Map<String,Object> map=new HashMap();
        map.put("inundation",inundationList);
        map.put("reservoirSubmergence",submergenceList);
        return map;
    }

    @Override
    public List<DeviceInfoVO> selectDeviceInfo() {
        return elementsDAO.selectDeviceInfo();
    }

    @Override
    public List<SectionDownstreamVO> selectElementsDownstream() {
        return elementsDAO.selectElementsDownstream();
    }
    @Override
    public List<SectionDownstreamVO> selectRelicPatternSpot() {
        return elementsDAO.selectRelicPatternSpot();
    }

    @Override
    public List<SectionDownstreamVO> selectVillageDate() {
        return elementsDAO.selectVillageDate();
    }


//    private List<ReservoirInundationDataVO> processInundationData(JSONArray jsonArray) {
//        return IntStream.range(0, jsonArray.size())
//                .mapToObj(i -> {
//                    JSONObject dateObj = jsonArray.getJSONObject(i);
//                    List<ReservoirInundationVO> inundationList = elementsDAO.selectReservoirInundationByWaterlevel(dateObj.getBigDecimal("waterLevelStart"));
//                    return buildReservoirInundationData(inundationList, dateObj.getInt("time"));
//                })
//                .collect(Collectors.toList());
//    }

    private List<ReservoirInundationDataVO> processSubmergenceData(Integer year, BigDecimal level, Integer status,List<VillageVO> village, List<RelicPatternSpotVO> elementsPatternSpotList) {
        if (year == 2020) {
            level = null;
        }

        List<ReservoirInundationDataVO> list = new ArrayList<>();
        List<ReservoirInundationVO> submergenceList = elementsDAO.selectReservoirSubmergenceByYearNew(year, level, status);


        if (submergenceList == null) {
            submergenceList = Collections.emptyList();
        }

// 根据 key 的实际类型选择合适的比较器
        Map<Integer, List<ReservoirInundationVO>> groupedByTime = submergenceList.stream()
                .collect(Collectors.groupingBy(
                        ReservoirInundationVO::getTime,
                        () -> new TreeMap<>(Comparator.naturalOrder()),  // 如果 key 是 Integer
                        Collectors.toList()
                ));

        groupedByTime.forEach((key, value) -> {
            list.add(buildReservoirSubmergenceData(value, key,village,elementsPatternSpotList));
        });
        return list;
    }

    private ReservoirInundationDataVO buildReservoirInundationData(List<ReservoirInundationVO> dataList, Integer time,List<VillageVO> village, List<RelicPatternSpotVO> elementsPatternSpotList) {
        List<ElementsReservoirAreaVO> elementsReservoirAreaList = elementsDAO.getElementsList();
        ReservoirInundationDataVO result = new ReservoirInundationDataVO();
        result.setTime(time);

        if (dataList == null || dataList.isEmpty()) {
            return result;
        }

        Map<Integer, List<ReservoirInundationVO>> dataByType = dataList.stream()
                .collect(Collectors.groupingBy(ReservoirInundationVO::getType));

        processTownVillageData(result, dataByType.get(1),village);

        processKqgjysData(result, dataByType.get(6), elementsReservoirAreaList);

        processWwtbData(result, dataByType.get(7),elementsPatternSpotList);
        List<ReservoirInundationVO> list = dataByType.getOrDefault(4, Collections.emptyList())
                .stream()
                .collect(Collectors.groupingBy(
                        item -> new AbstractMap.SimpleEntry<>(item.getVillage(), item.getTown()),
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                lists -> {
                                    // 计算两个字段的和
                                    BigDecimal areaSum = lists.stream()
                                            .map(item -> item.getArea() != null ? item.getArea() : BigDecimal.ZERO)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                                    Integer populationSum = lists.stream()
                                            .map(item -> item.getPopulation() != null ? item.getPopulation() : 0)
                                            .reduce(0, Integer::sum);

                                    // 创建结果对象
                                    ReservoirInundationVO vo = new ReservoirInundationVO();
                                    vo.setVillage(lists.get(0).getVillage());
                                    vo.setTown(lists.get(0).getTown());
                                    vo.setArea(areaSum);
                                    vo.setPopulation(populationSum);
                                    return vo;
                                }
                        )
                ))
                .values()  // 获取所有分组后的结果
                .stream()
                .collect(Collectors.toList());

        processPopulationStructureData(result,list);

        return result;
    }

    private ReservoirInundationDataVO buildReservoirSubmergenceData(List<ReservoirInundationVO> dataList,Integer time,List<VillageVO> village,List<RelicPatternSpotVO> elementsPatternSpotList) {
        List<ElementsReservoirAreaVO> elementsReservoirAreaList = elementsDAO.getElementsReservoirList();
        ReservoirInundationDataVO result = new ReservoirInundationDataVO();

        if (dataList == null || dataList.isEmpty()) {
            return result;
        }

        Map<Integer, List<ReservoirInundationVO>> dataByType = dataList.stream()
                .collect(Collectors.groupingBy(ReservoirInundationVO::getType));


        processTownVillageData(result, dataByType.get(3),village);


        processKqgjysData(result, dataByType.get(5), elementsReservoirAreaList);


        processWwtbData(result, dataByType.get(6),elementsPatternSpotList);

        result.setTime(time);
        processSubmergencePopulationStructureData(result, dataByType.get(1), dataByType.get(4));
       List<EmergencyVO> list= elementsDAO.selectEmergencyContact();

        result.setEmergencyList(list);
        return result;
    }

    private void processTownVillageData(ReservoirInundationDataVO result, List<ReservoirInundationVO> townVillageData,List<VillageVO> list) {
        if (townVillageData == null || townVillageData.isEmpty()) {
            return;
        }

        result.setTownCount((int) townVillageData.stream().map(ReservoirInundationVO::getTown).distinct().count());
        result.setVillageCount((int) townVillageData.stream().map(ReservoirInundationVO::getVillage).distinct().count());

        List<String> villages = townVillageData.stream()
                .map(ReservoirInundationVO::getVillage)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        List<VillageVO> village = list.stream()
                .filter(villageVO -> villages.contains(villageVO.getCMC()))
                .collect(Collectors.toList());
        result.setVillage(village);
    }

    private void processKqgjysData(ReservoirInundationDataVO result, List<ReservoirInundationVO> kqgjysData,  List<ElementsReservoirAreaVO> elements) {
        if (kqgjysData == null || kqgjysData.isEmpty()) {
            result.setGjCount(0);
            return;
        }

        result.setGjCount(kqgjysData.size());

        List<String> names = kqgjysData.stream()
                .map(ReservoirInundationVO::getName).distinct()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<ElementsReservoirAreaVO> element = elements.stream()
                .filter(ElementsReservoirAreaVO -> names.contains(ElementsReservoirAreaVO.getName()))
                .collect(Collectors.toList());
        result.setKqgjysList(element);
    }

    private void processWwtbData(ReservoirInundationDataVO result, List<ReservoirInundationVO> wwtbData, List<RelicPatternSpotVO> elementsPatternSpotList) {
        if (wwtbData == null || wwtbData.isEmpty()) {
            result.setWwCount(0);
            return;
        }

        result.setWwCount(wwtbData.size());

        List<String> names = wwtbData.stream()
                .map(ReservoirInundationVO::getName).distinct()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<RelicPatternSpotVO> element = elementsPatternSpotList.stream()
                .filter(RelicPatternSpotVO -> names.contains(RelicPatternSpotVO.getName()))
                .collect(Collectors.toList());

        result.setWwtbList(element);
    }

    private void processPopulationStructureData(ReservoirInundationDataVO result, List<ReservoirInundationVO> populationData) {
        if (populationData == null || populationData.isEmpty()) {
            result.setStructure(0);
            result.setPopulation(0);
            return;
        }

        result.setStructure(populationData.size());
        int totalPopulation = Optional.ofNullable(populationData)
                .orElseGet(Collections::emptyList)
                .stream()
                .filter(Objects::nonNull)
                .mapToInt(vo ->
                        Optional.ofNullable(vo.getPopulation()).orElse(0)  // 如果 getPopulation() 为 null，转为 0
                )
                .sum();

        result.setPopulation(totalPopulation);
        result.setPopulationList(populationData);
        result.setStructureList(populationData);
    }

    private void processSubmergencePopulationStructureData(ReservoirInundationDataVO result,
                                                           List<ReservoirInundationVO> structureData,
                                                           List<ReservoirInundationVO> populationData) {
        if (structureData != null) {
            result.setStructure(structureData.size());
            result.setStructureList(structureData);
        }

        if (populationData != null) {
            result.setPopulation(populationData.stream()
                    .mapToInt(ReservoirInundationVO::getPopulation)
                    .sum());
            result.setPopulationList(populationData);
        }
    }

    private ReservoirInundationStatsVO disposeStats(List<ReservoirInundationVO> reservoirInundationVOList, List<RelicPatternSpotVO> relicPatternSpotList) {
        ReservoirInundationStatsVO reservoirInundationStatsVO = new ReservoirInundationStatsVO();
        Map<Integer, List<ReservoirInundationVO>> reservoirInundationMap = reservoirInundationVOList.stream()
                .collect(Collectors.groupingBy(ReservoirInundationVO::getType));
        reservoirInundationStatsVO.setTownCount((int) reservoirInundationMap.get(1).stream().map(ReservoirInundationVO::getTown).distinct().count());
        reservoirInundationStatsVO.setVillageCount((int) reservoirInundationMap.get(1).stream().map(ReservoirInundationVO::getVillage).distinct().count());
        BigDecimal totalAcreage = reservoirInundationMap.getOrDefault(2, Collections.emptyList())
                .stream()
                .map(vo -> vo.getArea() != null ? vo.getArea() : BigDecimal.ZERO) // 处理null值
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .setScale(2, RoundingMode.HALF_UP);

        reservoirInundationStatsVO.setTotalAcreage(totalAcreage);

        List<ReservoirInundationVO> villageTotalAreaList = elementsDAO.selectVillageTotalAreaList(1, reservoirInundationVOList.get(0).getWaterlevel());
        Map<String, List<ReservoirInundationVO>> villageMap = villageTotalAreaList.stream().collect(Collectors.groupingBy(ReservoirInundationVO::getVillage));

        //库区关键要素
        List<ReservoirInundationVO> kqgjysList = reservoirInundationMap.get(6);
        reservoirInundationStatsVO.setKqgjysList(kqgjysList);
        reservoirInundationStatsVO.setGjCount(kqgjysList != null ? kqgjysList.size() : 0);
        //文物图斑
        List<ReservoirInundationVO> wwtbList = reservoirInundationMap.get(7);
        reservoirInundationStatsVO.setWwCount(wwtbList!= null ? wwtbList.size() : 0);
        for (RelicPatternSpotVO relicPatternSpotVO : relicPatternSpotList) {
            ReservoirInundationVO bi = new ReservoirInundationVO();
            bi.setName(relicPatternSpotVO.getName());
            bi.setCategory(relicPatternSpotVO.getCategory());
            bi.setYear(relicPatternSpotVO.getYear());
            bi.setDistrict(relicPatternSpotVO.getType());
            wwtbList.add(bi);
        }
        reservoirInundationStatsVO.setWwtbList(wwtbList);

        //影响建筑、人口
        List<ReservoirInundationVO> jzrkList = reservoirInundationMap.get(4);
        reservoirInundationStatsVO.setStructure(jzrkList.size());
        reservoirInundationStatsVO.setPopulation(jzrkList.stream().map(ReservoirInundationVO::getPopulation)
                .reduce(0, Integer::sum));

        Map<String, List<ReservoirInundationVO>> jzrkMap = jzrkList.stream().collect(Collectors.groupingBy(ReservoirInundationVO::getVillage));

        List<Map> villageTotal =new ArrayList<>();
        villageMap.forEach((key, list) -> {
            Map map = new HashMap<>();
            map.put("town", list.get(0).getTown());
            map.put("village", list.get(0).getVillage());
            if (jzrkMap.containsKey(list.get(0).getVillage())) {
                map.put("structure", jzrkMap.get(list.get(0).getVillage()).size());
                map.put("population", jzrkMap.get(list.get(0).getVillage()).stream().map(ReservoirInundationVO::getPopulation)
                        .reduce(0, Integer::sum));
            } else {
                map.put("structure", "");
                map.put("population", "");
            }
            map.put("totalArea", list.stream().map(ReservoirInundationVO::getArea).reduce(BigDecimal.ZERO, BigDecimal::add)
                    .setScale(2, RoundingMode.HALF_UP));

            for (ReservoirInundationVO reservoirInundationVO : list) {
                map.put(ReservoirInundationNameEnums.getByLandName(reservoirInundationVO.getName()).getFieldName(),
                        reservoirInundationVO.getArea());
            }
            for (ReservoirInundationNameEnums type : ReservoirInundationNameEnums.values()) {
                if (!map.containsKey(type.getFieldName())) {
                    map.put(type.getFieldName(), "");
                }
            }
            villageTotal.add(map);
        });
        reservoirInundationStatsVO.setVillageTotal(villageTotal);
        return reservoirInundationStatsVO;
    }

    @Override
    public List<ZSmallRsvrPositionVO> selectZSmallRsvrPositionDate() {
        return elementsDAO.selectZSmallRsvrPositionDate();
    }
    public List<EmergencyContactResponseVO> selectEmergencyContact() {
      List<EmergencyContactVO> contacts=  elementsDAO.selectEmergencyContactList();

        return groupContactsByVillage(contacts);
    }
    private List<EmergencyContactResponseVO> groupContactsByVillage(List<EmergencyContactVO> contacts) {
        Map<String, EmergencyContactResponseVO> groupedMap = new LinkedHashMap<>();

        for (EmergencyContactVO contact : contacts) {
            // 使用村镇组合作为key
            String key = contact.getTown() + "-" + contact.getVillage();

            // 如果该村镇还未在map中，创建新的响应对象
            if (!groupedMap.containsKey(key)) {
                EmergencyContactResponseVO response = new EmergencyContactResponseVO();
                response.setTown(contact.getTown());
                response.setVillage(contact.getVillage());
                response.setLat(contact.getLat());
                response.setLnt(contact.getLnt());
                response.setEl(contact.getEl());
                response.setContacts(new ArrayList<>());
                groupedMap.put(key, response);
            }

            // 添加联系人信息
            EmergencyContactResponseVO.ContactInfo contactInfo = new EmergencyContactResponseVO.ContactInfo();
            contactInfo.setName(contact.getName());
            contactInfo.setPhone(contact.getPhone());
            contactInfo.setType(contact.getType());

            groupedMap.get(key).getContacts().add(contactInfo);
        }

        // 转换为列表返回
        return new ArrayList<>(groupedMap.values());
    }
}
